<template>
  <!--分配角色-->
  <div class="search">
    <a-form :form="form" ref="roleForm">
      <f-form-item label="角色" :required="true" :rules="rules.checked(1)" name="roleIds" type="checkbox" :data="selectRoles"  label-key="roleName" value-key="roleId" :value="grantRoles"></f-form-item>
    </a-form>
  </div>
</template>

<script>
  import { getUserRoles, getAllRoles } from '@/api/manage'

  export default {
    name: 'userRole',
    props: {},
    data () {
      return {
        form: this.$form.createForm(this),
        selectRoles: [],
        userId: '',
        grantRoles: []

      }
    },
    methods: {
      setData (data) {
        if (data && data.userId) {
          this.userId = data.userId
          this.handleLoadRoles(data.userId)
        }
      },
      handleSubmit () {
        this.form.validateFields((valid, values) => {
          if (!valid) {
            this.http.post(this, {
              url: this.api.managerUser.setRole,
              data: {
                userId: this.userId,
                roleIds: values.roleIds.join(',')
              },
              success: function (me) {
                me.$bus.emit('closeModal')
              }
            })
          }
        })
      },
      handleLoadRoles (userId) {
        if (!userId) {
          return
        }
        const that = this
        const p1 = getAllRoles()
        const p2 = getUserRoles(userId)
        Promise.all([p1, p2]).then(function (values) {
          let res1 = values[0]
          let res2 = values[1]
          if (res1.code === that.http.HTTP_OK_STATUS) {
            that.selectRoles = res1.data
          }
          if (res2.code === that.http.HTTP_OK_STATUS) {
            let result = []
            res2.data.map(item => {
              result.push(item.roleId)
            })
            that.grantRoles = result
          }
        })
      }
    },
    created () {

    },
    components: {}
  }
</script>

<style scoped lang="less" rel="stylesheet/less">

</style>
